package utils

import (
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/chain-zhang/pinyin"
	"reflect"
	"strconv"
	"strings"
	"time"
)

func EnMd5(mstr string) string {

	data := []byte(mstr)
	md5obj := md5.New()
	md5obj.Write(data)
	res := md5obj.Sum(nil)
	return hex.EncodeToString(res)

}

func Sha1(data []byte) string {
	hash := sha1.New()
	hash.Write(data)
	return hex.EncodeToString(hash.Sum(nil))
}

// 定义字典
func MakeJson() map[string]interface{} {
	var ResJosn map[string]interface{}
	ResJosn = make(map[string]interface{})
	return ResJosn
}

// 创建一个字典数组
func MakeDicArray() []map[string]interface{} {
	resTree := make([]map[string]interface{}, 0)
	return resTree
}

// // 字符串转整型
// string转成int：
// int, err := strconv.Atoi(string)
// string转成int64：
// int64, err := strconv.ParseInt(string, 10, 64)
// int转成string：
// string := strconv.Itoa(int)
// int64转成string：
// string := strconv.FormatInt(int64,10)
func StringToInt(str string) int {
	res, _ := strconv.Atoi(str)
	return res
}

func StringToInt64(str string) int64 {
	res, _ := strconv.ParseInt(str, 10, 64)
	return res
}

func IntToString(data int) string {
	res := strconv.Itoa(data)
	return res
}

func Int64ToString(data int64) string {
	res := strconv.FormatInt(data, 10)
	return res
}

// 格式化error
func FormatErrorToString(err error) string {
	errors := fmt.Sprintf("%s", err)
	return errors
}

// 获取当前时间
func GetNowTime() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

// 截取字符串中的字符
func SubstrByByte(str string, length int) string {
	bs := []byte(str)[:length]
	bl := 0
	for i := len(bs) - 1; i >= 0; i-- {
		switch {
		case bs[i] >= 0 && bs[i] <= 127:
			return string(bs[:i+1])
		case bs[i] >= 128 && bs[i] <= 191:
			bl++
		case bs[i] >= 192 && bs[i] <= 253:
			cl := 0
			switch {
			case bs[i]&252 == 252:
				cl = 6
			case bs[i]&248 == 248:
				cl = 5
			case bs[i]&240 == 240:
				cl = 4
			case bs[i]&224 == 224:
				cl = 3
			default:
				cl = 2
			}
			if bl+1 == cl {
				return string(bs[:i+cl])
			}
			return string(bs[:i])
		}
	}
	return ""
}

// 汉字转拼音
func ChinesToPinyin() (string, error) {
	str, err := pinyin.New("我是中国人").Split("").Mode(pinyin.InitialsInCapitals).Convert()
	if err != nil {
		return "", err
	} else {
		return str, nil
	}
}

// 汉字转拼音输出首字母
func ChinesToPinyinInitial(content string) string {
	str, _ := pinyin.New(content).Split("").Mode(pinyin.InitialsInCapitals).Convert()
	return SubstrByByte(str, 1)
}

// 字典数组按key进行排序
func SortDictKeyZimu(arr []map[string]interface{}) []map[string]interface{} {
	maps := MakeJson()
	dest := make([]map[string]interface{}, 0)
	for i := 0; i < len(arr); i++ {
		ai := arr[i]
		key := ai["pin_yin"]
		if maps[key.(string)] == nil {
			tempArr := make([]map[string]interface{}, 0)
			tempArr = append(tempArr, ai)
			tempMap := MakeJson()
			tempMap["pin_yin"] = ai["pin_yin"]
			tempMap["children"] = tempArr
			dest = append(dest, tempMap)
			maps[ai["pin_yin"].(string)] = ai
		} else {
			for j := 0; j < len(dest); j++ {
				dj := dest[j]
				if dj["pin_yin"] == ai["pin_yin"] {
					dj["children"] = append(dj["children"].([]map[string]interface{}), ai)
					break
				}
			}
		}
	}
	return dest
}

// 获取第n天函数
func GetDateOfNday(n int) string {
	currentTime := time.Now()
	oldTime := currentTime.AddDate(0, 0, n).Format("2006-01-02")
	return oldTime
}

// 版本生成
func VersionCrate(num int, base int) string {
	//低位处理
	lz := num / base
	ly := num % base
	//中数处理
	middle := lz
	mz := middle / base
	my := middle % base
	//中数处理
	high := mz
	st1 := strconv.Itoa(ly)
	st2 := strconv.Itoa(my)
	st3 := strconv.Itoa(high)
	return "v" + st3 + "." + st2 + "." + st1
}

func Duplicate(a interface{}) (ret []interface{}) {
	va := reflect.ValueOf(a)
	for i := 0; i < va.Len(); i++ {
		if i > 0 && reflect.DeepEqual(va.Index(i-1).Interface(), va.Index(i).Interface()) {
			continue
		}
		ret = append(ret, va.Index(i).Interface())
	}
	return ret
}

// 数组变字符串
func ObjectToString(object []interface{}) string {
	b, err := json.Marshal(object)
	if err != nil {
		panic(err)
	}
	var result = string(b)
	return result
}

// 按版本分类
func SortDictVersion(arr []map[string]interface{}) []map[string]interface{} {
	maps := MakeJson()
	dest := make([]map[string]interface{}, 0)
	for i := 0; i < len(arr); i++ {
		ai := arr[i]
		key := ai["version"]
		if maps[key.(string)] == nil {
			tempArr := make([]map[string]interface{}, 0)
			tempArr = append(tempArr, ai)
			tempMap := MakeJson()
			tempMap["version"] = ai["version"]
			tempMap["children"] = tempArr
			dest = append(dest, tempMap)
			maps[ai["version"].(string)] = ai
		} else {
			for j := 0; j < len(dest); j++ {
				dj := dest[j]
				if dj["version"] == ai["version"] {
					dj["children"] = append(dj["children"].([]map[string]interface{}), ai)
					break
				}
			}
		}
	}
	return dest
}

func SortDictTitle(arr []map[string]interface{}) []map[string]interface{} {
	maps := MakeJson()
	dest := make([]map[string]interface{}, 0)
	for i := 0; i < len(arr); i++ {
		ai := arr[i]
		key := ai["title"]
		if maps[key.(string)] == nil {
			tempArr := make([]map[string]interface{}, 0)
			tempArr = append(tempArr, ai)
			tempMap := MakeJson()
			tempMap["title"] = ai["title"]
			tempMap["children"] = tempArr
			dest = append(dest, tempMap)
			maps[ai["title"].(string)] = ai
		} else {
			for j := 0; j < len(dest); j++ {
				dj := dest[j]
				if dj["title"] == ai["title"] {
					dj["children"] = append(dj["children"].([]map[string]interface{}), ai)
					break
				}
			}
		}
	}
	return dest
}

// 数组转字符串
func NumberArrayToString(arr []int64) string {
	var result = ""
	if len(arr) == 0 {
		result = ""
	} else if len(arr) == 1 {
		result = strconv.FormatInt(arr[0], 10)
	} else {
		for j, i := range arr {
			if j < len(arr)-1 {
				result += strconv.FormatInt(i, 10) + ";"
			} else {
				result += strconv.FormatInt(i, 10)
			}
		}
	}
	return result
}

func StringToArrayByStr(str string) []string {
	arr := strings.Split(str, ";")
	return arr
}
